// import { XController, XJsonController } from '../../../lib/helper';
// import { Get, UseBefore, Render, Redirect, Post, BodyParam, Body, Session, Controller } from 'routing-controllers';
// import { CheckIfNotLoginErrorHandler, CheckIfLoginErrorHandler } from "../external/login";
import { ProxyUser } from '../ml/proxy_user';
import { V, Connection } from 'x-engine';
import { X } from "x-orm";
import { failed, SetCache, UUID, success, GetCache } from '../../../lib/utils';
import { md5, number_format } from 'locutus/php/strings';
import { VrOrder } from '../ml/order';
import { COrderStatus } from '../../../collect';
import { ProxyMargin } from '../ml/proxy_margin';
import { time, date } from 'locutus/php/datetime';
import { ProxyMember } from '../ml/proxy_member';
import { QianyingPayment } from '../payment/qianying';
import { Response, Request } from 'express';
import { MbUserToken } from '../ml/mb_user_token';

// @XJsonController


@V.Controller({
    type: Connection.HTTP,
    url: "/proxy/api/:method",
    dataType: "json",
})
export class ProxyAPI {

    async login(username: string, password: string, session: any) {
        console.log(username, password)

        const user = await X.of(ProxyUser).findOne({
            where: {
                name: username,
                password: (password)
            }
        })
        if (!user) {
            return failed();
        }
        const token = UUID();
        SetCache("proxy:token:" + token, user.id);
        session.proxy_token = token;
        return success();
    }



    /**
     * 支付成功回调接口
     */
    async order_pay_success(
        token: string,
        order_sn: string
    ) {
        if (token != '1q2w3e4r' || !order_sn) {
            return failed();
        }
        /**
         * 校验订单
         */
        let oinfo = await X.of(VrOrder).findOne({
            where: {
                order_sn: order_sn,
                order_state: 20,
                caipiao_status: COrderStatus.notopen
            },
            addon: {
                proxy_parent: 1
            }
        });

        if (!oinfo) {
            return failed('no order');
        }
        /**
         * 是否已经计算过提成
         */
        if (await X.of(ProxyMargin).count({
            where: {
                order_id: oinfo.order_id
            }
        })) {
            return failed();
        }

        //查找当前买卖所属代理
        let proxy = oinfo.proxy_parent;
        if (!proxy) {
            return failed();
        }
        //直属管理员，不计算提成
        if (proxy.id == 1) {
            return failed();
        }

        //找到最上级
        let item = proxy;
        let arr = [];
        try {
            while (true) {
                arr.push(item);
                await X.makeAddon(item, 'parent');
                if (!item || !item.parent || item.parent.id == 1) {
                    break;
                }
                item = item.parent;
            }
        }
        catch (e) {
            arr = [];
        }

        arr = arr.reverse();
        if (!arr.length || arr[0].type != 'normal') {
            return failed('not normal');
        }

        let goods_amount = (oinfo.order_amount - oinfo.s_fee - oinfo.f_fee);
        let fee = oinfo.s_fee;
        const moneys = [];
        // console.log(goods_amount)
        //预分配
        for (let i = 0; i < arr.length; i++) {
            //只有综合会员和经纪会员有货款分摊比例
            if (i == 0 || i == 1) {
                goods_amount = returnFloat(goods_amount * arr[i].fentan / 100)
                fee = returnFloat(fee * arr[i].shouxufei / 100);
                moneys.push([arr[i].id, Number(goods_amount) + Number(fee)]);
            }
            else {
                fee = returnFloat(fee * arr[i].shouxufei / 100);
                moneys.push([arr[i].id, Number(fee)]);
                // moneys[arr[i].id] = fee;
            }
            //减掉前一个的
            if (i > 0) {
                moneys[i - 1][1] -= moneys[i][1];
            }
        }

        try {
            await X.transition(async x => {
                for (const [id, money] of moneys) {
                    let info = await x.of(ProxyUser).findOne(id);
                    info.money += money;
                    await x.save(info);
                    // await X.query(`update nw_proxy_user set money = money + ${moneys[id]} where id = ${id}`);
                }
                let margin = new ProxyMargin;
                margin.order_id = oinfo.order_id;
                margin.phone = oinfo.buyer_phone;
                let count = 0;
                let types = ['normal', 'jingji', 'jigou', 'jujian'];
                for (let i = 0; i < 4; i++) {
                    if (moneys[i]) {
                        margin[types[i] + '_id'] = moneys[i][0];
                        margin[types[i] + '_money'] = moneys[i][1];
                    }
                    else {
                        margin[types[i] + '_id'] = 0;
                        margin[types[i] + '_money'] = 0;
                    }
                }
                margin.add_time = time();
                await x.save(margin);
            })


        } catch (e) {

        }
        console.log(moneys);

        // console.log(margin)
        return success();
    }





    // @OrmRepository(ProxyUser)
    // proxyuserR : Repository<ProxyUser>

    // @Get("/admin/login.html")
    // @UseBefore(CheckIfNotLoginErrorHandler)
    // @Render('admin/login.html')
    // login(){

    // }

    // @Get('admin/')
    // @UseBefore(CheckIfLoginErrorHandler)
    // @Redirect("/admin/index.html")
    // main(){
    //     console.log("fuck")
    // }


    // @Post('/admin/login')
    // async doLogin(
    //     @BodyParam('username') name : string,
    //     @BodyParam('password') password : string,
    //     @Session() session
    // ){
    //     // console.log(body);
    //     // return;
    //     var uinfo = await this.proxyuserR.findOne({
    //         where : {
    //             name : name,
    //             password : md5(password)
    //         }
    //     });
    //     console.log(uinfo);
    //     if(uinfo){
    //         var token = UUID();
    //         SetCache("lk_admin_token:" + token,uinfo.id);
    //         session.lk_admin_token = token;
    //         return success();
    //     }
    //     return failed();

    // }



    /**
     * 最新参与记录
     */
    async new_buyers() {
        let orders =  await X.of(VrOrder).find({
            where: {
            },
            order: {
                add_time: 'desc'
            },
            limit : 20
        });

        let ret = orders.map(item => {
            return {
                time : date("Y-m-d H:i:s",item.add_time),
                buyer_id : item.buyer_id,
                buyer_name : item.buyer_name,
                num : item.goods_num,
                goods : item.goods_name,
                guess : item.guess
            }
            // item.add_time = 

        });
        return ret;
    }

    /**
     * 展开前应支付接口
     */
    async pay_order_qianying(
        res : Response,
        req : Request,
        orderId?,
        orderAmount?,
        returnUrl?,
        callbackUrl?,
        failedUrl?
    ){
        // if(!orderId || !orderAmount || !returnUrl || !callbackUrl || !failed){
        //     // res.redirect()
        //     // res.headersSent
        //     res.send("<script>history.back()</script>") 
        //     // res.redirect(req.headers);
        //     return ;
        // //     return failed('参数不对');
        // }
        const url = new QianyingPayment(1349,'41c43e66a8db4199a8a12d238fe4b6f1','http://www.baidu.com','http://www.baidu.com').buildPayUrl(101,time(),100,"http://www.baidu.com");
        
        res.redirect(url);
        // return success({
            // url
        // });
    }



   



    
}


function returnFloat(value) {
    value = Math.floor(parseFloat(value) * 100) / 100;
    var xsd = value.toString().split(".");
    if (xsd.length == 1) {
        value = value.toString() + ".00";
        return value;
    }
    if (xsd.length > 1) {
        if (xsd[1].length < 2) {
            value = value.toString() + "0";
        }
        return value;
    }
}

